using UnityEngine;

namespace DOTS
{
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        static T mInstance;

        public static T Instance
        {
            get
            {
                if (mInstance == null)
                {
                    //根据类型 T 搜索实例
                    T[] instanceArray = FindObjectsOfType<T>();
                    string typeName = typeof(T).Name;

                    //场景中 无实例
                    if (instanceArray == null || instanceArray.Length == 0)
                    {
                        //根据类型名搜索场景中 GameObject
                        GameObject instanceObj = GameObject.Find(typeName);

                        if (instanceObj == null) //无同名 GameObject
                        {
                            instanceObj = new GameObject(typeName);
                            DontDestroyOnLoad(instanceObj); //切换场景 单例不销毁
                        }

                        mInstance = instanceObj.AddComponent<T>(); //添加实例
                    }
                    //场景中 有一个实例
                    else if (instanceArray.Length == 1)
                    {
                        mInstance = instanceArray[0];
                    }
                    //场景中 有多个实例
                    else
                    {
                        Debug.LogWarning($"存在多个 GameObject 挂载有单例：{typeof(T)}");
                        mInstance = instanceArray[0];
                    }
                }

                return mInstance;
            }
        }
    }
}